package com.xzg.handlerAdapter;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xzg.annotation.XzgService;
import com.xzg.argumentResolver.ArgumentResolver;

@XzgService("XzgHandlerAdapter")
public class XzgHandlerAdapter implements HandlerAdapterService {

	public Object[] hand(HttpServletRequest request, HttpServletResponse response, Method method,
			Map<String, Object> beans) {
		// 先获取方法上的所有参数类型集合
		Class<?>[] paramClazzs = method.getParameterTypes();
		Object[] args = new Object[paramClazzs.length];
		int index = 0;
		int i = 0;
		Map<String, Object> resolverBean = getBeansOfType(beans, ArgumentResolver.class);
		// 遍历所有的参数类型
		for (Class<?> clazz : paramClazzs) {
			for (Map.Entry<String, Object> entry : resolverBean.entrySet()) {
				ArgumentResolver ar = (ArgumentResolver) entry.getValue();
				if (ar.support(clazz, index, method)) {
					args[i++] = ar.argumentResolver(clazz, index, method, request, response);
				} else {
					continue;
				}
				index++;
			}
		}
		return args;
	}

	private Map<String, Object> getBeansOfType(Map<String, Object> beans, Class<?> class1) {
		Map<String, Object> bean = new HashMap<String, Object>();
		for (Map.Entry<String, Object> entry : beans.entrySet()) {
			Class<?>[] clazz = entry.getValue().getClass().getInterfaces();
			if (clazz != null && clazz.length > 0) {
				for (Class<?> class2 : clazz) {
					if (class2.isAssignableFrom(class1)) {
						bean.put(entry.getKey(), entry.getValue());
					} else {
						continue;
					}
				}
			}
		}
		return bean;
	}

}
